package gang.com.mobelhelper.common.rx;


import android.util.Log;

import gang.com.mobelhelper.bean.BaseBeano;
import gang.com.mobelhelper.common.exception.ApiException;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/11/22.
 */

public class RxHttpRespCompat {
    public static <T> Observable.Transformer<BaseBeano<T>, T> compatResult() {
        return new Observable.Transformer<BaseBeano<T>, T>() {
            @Override
            public Observable<T> call(Observable<BaseBeano<T>> baseBeanObservable) {
                return baseBeanObservable.flatMap(new Func1<BaseBeano<T>, Observable<T>>() {
                    @Override
                    public Observable<T> call(final BaseBeano<T> tBaseBeano) {
                        Log.e("数据数据你哪去了", tBaseBeano.toString());
                        Log.e("数据数据你哪去了", tBaseBeano.toString());
                        Log.e("数据数据你哪去了", tBaseBeano.toString());
                        if (tBaseBeano.success()) {
                            return Observable.create(new Observable.OnSubscribe<T>() {
                                @Override
                                public void call(Subscriber<? super T> subscriber) {

                                    try {
                                        subscriber.onNext(tBaseBeano.getData());
                                        subscriber.onCompleted();
                                    } catch (Exception e) {
                                        subscriber.onError(e);
                                    }


                                }
                            });


                        } else {
                            return Observable.error(new ApiException(tBaseBeano.getStatus(), tBaseBeano.getMessage()));
                        }

                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
            }
        };


    }

}
